package com.lly.songhigh.volley;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.lly.songhigh.application.BaseApplication;

/**
 * Created by dllo on 15/9/23.
 */
public class VolleySingleton {

    private static final Object TAG = "VolleySingleton";
    private static VolleySingleton volleySingleton;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    // 构造方法私有, 防止其他类通过new创建对象
    private VolleySingleton() {
        requestQueue = getRequestQueue();
        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {

            LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(8*1024*1024);
            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }

    // 提供一个静态方法, 获取本类的实例
    public static VolleySingleton getInstance(){
        if (volleySingleton == null) {
            synchronized (VolleySingleton.class){
                if (volleySingleton == null) {
                    volleySingleton = new VolleySingleton();
                }
            }
        }
        return volleySingleton;
    }

    private RequestQueue getRequestQueue() {
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(BaseApplication.getContext());
        }
        return requestQueue;
    }

    // 提供一个方法, 将request加入到请求队列中
    public <T> void addQueue(Request<T> request, String tag){
        request.setTag(tag);
        getRequestQueue().add(request);
    }

    public <T> void addQueue(Request<T> request) {
        request.setTag(TAG);
        getRequestQueue().add(request);
    }

    // 将request移除请求队列, 取消网络请求
    public void removeQueue(Object object) {
        getRequestQueue().cancelAll(object);
    }
}
